<template>
  <!-- {{ customers }} -->
  <!-- 客户查询 -->
  <el-form :inline="true" :model="searchData" class="demo-form-inline">
    <el-form-item label="客户类型">
      <el-select
        v-model="searchData.ctId"
        clearable
        placeholder="客户类型"
        style="width: 240px"
      >
        <el-option
          v-for="item in customerType"
          :key="item.Id"
          :label="item.Value"
          :value="item.Id"
        />
      </el-select>
      <el-form-item label="手机号">
        <el-input
          v-model="searchData.tel"
          placeholder="请输入手机号"
          clearable
        />
      </el-form-item>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="GetCustomerList">查询</el-button>
      <el-button type="success" @click="DialogAdd">添加客户</el-button>
      <el-button type="info" @click="Export">导出客户信息</el-button>
    </el-form-item>
  </el-form>

  <!-- 客户列表 -->
  <el-table :data="customers" style="width: 100%">
    <el-table-column prop="CName" label="姓名"></el-table-column>
    <el-table-column prop="CtName" label="客户类型"></el-table-column>
    <el-table-column prop="CAge" label="年龄"></el-table-column>
    <el-table-column prop="Tel" label="电话" width="100"></el-table-column>
    <el-table-column prop="CAddress" label="地址" width="100"></el-table-column>
    <el-table-column prop="Birthday" label="出生日期">
      <template v-slot="scope">
        {{ scope.row.Birthday.substr(0, 10) }}
      </template>
    </el-table-column>
    <el-table-column prop="Tag" label="标签"></el-table-column>
    <el-table-column prop="IdCardNumber" label="身份证号"></el-table-column>
    <el-table-column prop="Consumption" label="消费金额">
      <template v-slot="scope">
        ￥<b style="color: red">{{ scope.row.Consumption.toFixed(2) }}</b>
      </template>
    </el-table-column>
    <el-table-column prop="Balance" label="余额">
      <template v-slot="scope">
        ￥<b style="color: red">{{ scope.row.Balance.toFixed(2) }}</b>
      </template>
    </el-table-column>
    <el-table-column prop="Integral" label="积分"></el-table-column>
    <el-table-column label="是否冻结">
      <template #default="scope">
        <el-tag :type="scope.row.IsFreeze ? 'danger' : 'success'">{{
          scope.row.IsFreeze ? "是" : "否"
        }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template v-slot="scope">
        <el-button
          link
          type="primary"
          size="small"
          @click="SkipDelital(scope.row.CId)"
          >详情</el-button
        >
        <el-button
          link
          type="primary"
          size="small"
          @click="DialogUpd(scope.row.CId)"
          >修改</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <table style="margin: 5px auto">
    <tbody>
      <tr>
        <td>
          <el-pagination
            v-model:current-page="page.page"
            v-model:page-size="page.size"
            :page-sizes="[10, 20, 40, 60]"
            layout="total, slot,sizes"
            :total="page.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            prev-text="上一页"
            next-text="下一页"
          >
            <span class="el-pagination__total is-first"
              >&nbsp;共计{{ page.pageCount }}页,当前{{ page.page }}/{{
                page.pageCount
              }}页</span
            >
          </el-pagination>
        </td>
        <td>
          <el-pagination
            v-model:current-page="page.page"
            v-model:page-size="page.size"
            :page-sizes="[10, 20, 40, 60]"
            layout="slot, prev, pager"
            :total="page.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            prev-text="上一页"
            next-text="下一页"
          >
            <button
              @click="handleCurrentChange(1)"
              :disabled="page.page == 1"
              class="btn-prev"
            >
              首页
            </button>
          </el-pagination>
        </td>
        <td>
          <el-pagination
            v-model:current-page="page.page"
            v-model:page-size="page.size"
            :page-sizes="[10, 20, 40, 60]"
            layout="slot, next, jumper"
            :total="page.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            prev-text="上一页"
            next-text="下一页"
          >
            <button
              @click="handleCurrentChange(page.pageCount)"
              :disabled="page.page == page.pageCount"
              class="next-prev"
            >
              尾页
            </button>
          </el-pagination>
        </td>
      </tr>
    </tbody>
  </table>

  <!-- 添加弹出框 -->
  <el-dialog v-model="dialogFormVisible" title="添加客户" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户类型" prop="CtId">
            <el-select v-model="form.CtId" placeholder="请选择客户类型">
              <el-option
                v-for="item in customerType"
                :key="item.Id"
                :label="item.Value"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="CName">
            <el-input v-model="form.CName" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="年龄" prop="CAge">
            <el-input v-model="form.CAge" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="Tel">
            <el-input v-model="form.Tel" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="标签" prop="Tag">
            <el-input v-model="form.Tag" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可用积分" prop="Integral">
            <el-input v-model="form.Integral" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="消费金额" prop="Consumption">
            <el-input v-model="form.Consumption" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消费次数" prop="CumulativeNumber">
            <el-input v-model="form.CumulativeNumber" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="是否冻结">
            <el-radio-group v-model="form.IsFreeze">
              <el-radio :value="false">否</el-radio>
              <el-radio :value="true">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" required>
            <el-form-item prop="Birthday">
              <el-date-picker
                v-model="form.Birthday"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="CAddress">
            <el-input v-model="form.CAddress" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国家" prop="NationId">
            <el-select v-model="form.NationId" placeholder="请选择国家">
              <el-option
                v-for="item in nationality"
                :key="item.Id"
                :label="item.Value"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="身份证号" prop="IdCardNumber">
            <el-input v-model="form.IdCardNumber" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="AddCustomer(ruleFormRef)">
          添 加
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 修改弹出框 -->
  <el-dialog v-model="UpddialogFormVisible" title="修改客户" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户类型" prop="CtId">
            <el-select v-model="form.CtId" placeholder="请选择客户类型">
              <el-option
                v-for="item in customerType"
                :key="item.Id"
                :label="item.Value"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="CName">
            <el-input v-model="form.CName" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="年龄" prop="CAge">
            <el-input v-model="form.CAge" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="Tel">
            <el-input v-model="form.Tel" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="标签" prop="Tag">
            <el-input v-model="form.Tag" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可用积分" prop="Integral">
            <el-input v-model="form.Integral" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="消费金额" prop="Consumption">
            <el-input v-model="form.Consumption" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消费次数" prop="CumulativeNumber">
            <el-input v-model="form.CumulativeNumber" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="余额" prop="Balance">
            <el-input v-model="form.Balance" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="累计消费" prop="AccumulativeConsumption">
            <el-input v-model="form.AccumulativeConsumption" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="是否冻结">
            <el-radio-group v-model="form.IsFreeze">
              <el-radio :value="false">否</el-radio>
              <el-radio :value="true">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" required>
            <el-form-item prop="Birthday">
              <el-date-picker
                v-model="form.Birthday"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="CAddress">
            <el-input v-model="form.CAddress" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国家" prop="NationId">
            <el-select v-model="form.NationId" placeholder="请选择国家">
              <el-option
                v-for="item in nationality"
                :key="item.Id"
                :label="item.Value"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="身份证号" prop="IdCardNumber">
            <el-input v-model="form.IdCardNumber" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="UpdCustomer(ruleFormRef)">
          修 改
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
// 引入组件
import { ElTable } from "element-plus";
import { reactive, ref, onMounted } from "vue";
//引入路由
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

axios.defaults.baseURL = "http://localhost:5089/api/";

//路由变量
const router = useRouter();

//当前页面路由
const route = useRoute();

//定义变量
//表单校验
const ruleFormRef = ref<FormInstance>();
const dialogFormVisible = ref(false);
const UpddialogFormVisible = ref(false);

// 客户数据
const form = reactive({
  CId: 0,
  CName: "",
  Tel: "",
  Tag: "",
  Balance: 0,
  Integral: "",
  Consumption: "",
  AccumulativeConsumption: 0,
  CumulativeNumber: "",
  IsFreeze: false,
  Birthday: "",
  IdCardNumber: "",
  CAge: "",
  TenantId: "default",
  CAddress: "",
  CtId: 27,
  NationId: "",
});

// 校验规则
const rules = reactive<FormRules>({
  CName: [
    { required: true, message: "请输入客户名称", trigger: "blur" },
    { min: 2, max: 20, message: "字符串长度介于2-20之间", trigger: "blur" },
  ],
  CAge: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && !/^\d+$/.test(value)) {
          callback(new Error("年龄必须是数字，不能包含汉字"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  Tel: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[345789]\d{9}$/,
      message: "手机号码格式不正确",
      trigger: "blur",
    },
  ],
  Tag: [{ required: true, message: "请输入标签", trigger: "blur" }],
  Balance: [{ required: true, message: "请输入可用余额", trigger: "blur" }],
  AccumulativeConsumption: [
    { required: true, message: "请输入累计消费金额", trigger: "blur" },
  ],
  CumulativeNumber: [
    { required: true, message: "请输入消费次数", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && !/^\d+$/.test(value)) {
          callback(new Error("消费次数必须是数字，不能包含汉字"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  Integral: [
    { required: true, message: "请输入可用积分", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && !/^\d+$/.test(value)) {
          callback(new Error("积分必须是数字，不能包含汉字"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  Consumption: [
    { required: true, message: "请输入消费金额", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && !/^\d+$/.test(value)) {
          callback(new Error("消费金额必须是数字，不能包含汉字"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  birthday: [
    {
      required: true,
      message: "请选择出生日期",
      trigger: "change",
    },
  ],
  IdCardNumber: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "身份证号码格式不正确",
      trigger: "blur",
    },
  ],
  CAddress: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
});

//查询条件
const searchData = reactive({
  ctId: "",
  tel: "",
});
// 分页条件
const page = reactive({
  page: 1,
  size: 10,
  totalCount: 0,
  pageCount: 0,
});
const customerType = ref([{ Id: Number, Value: String }]);
const nationality = ref([{ Id: Number, Value: String }]);
const customers = ref([]);

//方法
// 客户添加
const AddCustomer = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      axios.post("Customer/CustomerAdd", form).then((res) => {
        if (res.data.Code == 200) {
          ElMessage.success("添加成功！");
          dialogFormVisible.value = false;
          //刷新列表
          GetCustomerList();
        } else {
          ElMessage.error("添加失败或已有相同客户！");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogFormVisible.value = false;
};

//弹出修改框
const DialogUpd = (cId: string) => {
  UpddialogFormVisible.value = true;

  sessionStorage.setItem("CId", cId);

  GetCustomerData();
};

//客户信息反填
const GetCustomerData = () => {
  var CId = sessionStorage.getItem("CId");
  console.log(CId);
  axios.get("Customer/GetCustomerDelital?cId=" + CId).then((res) => {
    let d = res.data;
    console.log(d);
    form.CId = d.CId;
    form.CName = d.CName;
    form.Tel = d.Tel;
    form.Tag = d.Tag;
    form.Balance = d.Balance;
    form.Integral = d.Integral;
    form.Consumption = d.Consumption;
    form.AccumulativeConsumption = d.AccumulativeConsumption;
    form.CumulativeNumber = d.CumulativeNumber;
    form.IsFreeze = d.IsFreeze;
    form.Birthday = d.Birthday;
    form.IdCardNumber = d.IdCardNumber;
    form.CAge = d.CAge;
    form.TenantId = "default";
    form.CAddress = d.CAddress;
    form.CtId = d.CtId;
    form.NationId = d.NationId;
  });
};

//客户修改
const UpdCustomer = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      axios.post("Customer/UpdCustomer", form).then((res) => {
        if (res.data.Code == 200) {
          ElMessage.success("修改成功！");
          UpddialogFormVisible.value = false;
          //刷新列表
          GetCustomerList();
        } else {
          ElMessage.error("修改失败！");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 获取客户类型下拉
const GetcustomerTypeList = () => {
  axios.get("Dic/DicShow?Identification=customertype").then((res) => {
    customerType.value = res.data;
  });
};

// 获取国家下拉
const GetnationalityList = () => {
  axios.get("Dic/DicShow?Identification=country").then((res) => {
    nationality.value = res.data;
  });
};

//获取客户信息
function GetCustomerList() {
  axios
    .get("Customer/CustomerInfoList", {
      params: {
        ctId: searchData.ctId || 0,
        tel: searchData.tel || "",
        pageIndex: page.page,
        pageSize: page.size,
      },
    })
    .then((res) => {
      // console.log(res.data);
      customers.value = res.data.Data;
      page.totalCount = res.data.TotalCount;
      page.pageCount = res.data.PageCount;
    });
}

//页容量变化
const handleSizeChange = (val: number) => {
  page.size = val;
  //刷新列表
  GetCustomerList();
};

//页序号变化
const handleCurrentChange = (val: number) => {
  page.page = val;
  //刷新列表
  GetCustomerList();
};

//弹出添加框
const DialogAdd = () => {
  dialogFormVisible.value = true;
};

//跳转到详情
const SkipDelital = (CId: number) => {
  router.push("CustomerDelital?cId=" + CId);
};

//文件导出
function Export() {
  axios({
    method: "post",
    url: "Customer/ExportCustomer",
    data: {},
    //设置请求头的 Content-Type 为 “application/json;charset=UTF-8”
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
    },
    //设置响应的 responseType 为 “blob”，表示返回的数据是二进制数据
    responseType: "blob",
  })
    .then((res) => {
      console.log(res, "res");
      //创建一个 Blob 对象来存储数据
      const blob = new Blob([res.data]);
      //使用 URL.createObjectURL() 方法生成一个 URL，指向这个 Blob 对象
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      //创建一个<a>标签，设置其href属性为这个URL，download属性为要下载的文件名
      link.download = "用户数据导出.xlsx";
      //触发<a>标签的点击事件
      link.click();
      //URL.revokeObjectURL()方法释放这个URL对象
      URL.revokeObjectURL(url);
    })
    .catch((err) => {});
}

//钩子函数
onMounted(() => {
  GetcustomerTypeList();
  GetnationalityList();
  GetCustomerList();
  GetCustomerData();
});
</script>

<style scoped></style>
